package com.zhiyou.aifeng.smart_machine

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.MotionEvent
import com.aifeng.utils.getExtra
import com.baidu.mapapi.*
import com.baidu.mapapi.isAvilible
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.zhiyou.aifeng.common.base.*
import com.zhiyou.aifeng.common.helper.*
import com.zhiyou.aifeng.common_ui.base.BaseActivity
import com.zhiyou.aifeng.common_ui.model.BaseUrl
import com.zhiyou.aifeng.common_ui.utils.showHintDialog
import com.zhiyou.aifeng.view.ImageAdapter
import com.zhiyou.aifeng.viewmodel.RepairViewModel
import com.zhpan.bannerview.BannerViewPager
import com.zhpan.bannerview.BaseViewHolder
import com.zhpan.indicator.enums.IndicatorSlideMode
import com.zhpan.indicator.enums.IndicatorStyle
import kotlinx.android.synthetic.main.activity_repair_detail.*
import org.jetbrains.anko.toast
import org.json.JSONObject

class RepairDetailActivity : BaseActivity() {

    private lateinit var mViewPager: BannerViewPager<String, BaseViewHolder<String>>
    private var mTel = ""
    private var mLat = ""
    private var mLng = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_repair_detail)
        setTransparentAndToolbar(isDarkFont = false)
        initTitle()

        getData()
    }

    override fun getViewModel() = get<RepairViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        mViewPager = find(R.id.repair_banner)
        mViewPager.apply {
            adapter = ImageAdapter()
            setIndicatorStyle(IndicatorStyle.CIRCLE)
            setIndicatorSlideMode(IndicatorSlideMode.NORMAL)
            setIndicatorSliderGap(dp2px(9f))
            setIndicatorSliderWidth(dp2px(7f))
            setIndicatorHeight(dp2px(7f))
            setIndicatorSliderColor(
                getColorEx(R.color.lighter),
                getColorEx(R.color.colorAccent)
            )
            setPageMargin(dp2px(15f))
            setInterval(5000)
            setScrollDuration(500)
        }.create()

        initMapView()

        repair_tel.oneClick {
            if (mTel.isNotEmpty()) {
                showHintDialog(
                    title = "提示",
                    hint = "确定要拨打联系维修电话吗？"
                ) { makeCall(mTel) }
            }
        }
        repair_call.oneClick {
            if (mTel.isNotEmpty()) {
                showHintDialog(
                    title = "提示",
                    hint = "确定要拨打联系维修电话吗？"
                ) { makeCall(mTel) }
            }
        }
        repair_nav.oneClick {
            if (mLat.isNotEmpty() && mLng.isNotEmpty()) {
                when {
                    isAvilible("com.baidu.BaiduMap") -> {
                        toBaiduDirection(
                            destination = "${mLat},$mLng",
                            src = "andr.aifeng.smart_machine",
                            coord_type = "wgs84"
                        )
                    }
                    isAvilible("com.autonavi.minimap") -> {
                        val values = LatLngHelper.gps84ToGcj02(mLat.toNotDouble(), mLng.toNotDouble())
                        toAMapRoute(
                            sourceApplication = "smart_machine",
                            dlat = values[0].toString(),
                            dlon = values[1].toString()
                        )
                    }
                    isAvilible("com.tencent.map") -> {
                        val values = LatLngHelper.gps84ToGcj02(mLat.toNotDouble(), mLng.toNotDouble())
                        toTenCentRoute(tocoord = "${values[0]},${values[1]}")
                    }
                    else -> toast("请安装地图软件！")
                }
            }
        }
    }

    private fun initMapView() {
        repair_map.apply {
            //隐藏百度Logo
            getChildAt(1).invisible()
            //隐藏缩放控件
            showZoomControls(false)
            //隐藏比例尺
            showScaleControl(false)
            map.apply {
                //普通地图
                mapType = BaiduMap.MAP_TYPE_NORMAL
                //开启定位图层
                isMyLocationEnabled = true
                //隐藏指南针
                uiSettings.isCompassEnabled = false
                //是否启用地图俯视功能
                uiSettings.isOverlookingGesturesEnabled = false

                setMyLocationConfiguration(
                    MyLocationConfiguration(
                        MyLocationConfiguration.LocationMode.NORMAL,
                        false,
                        null
                    )
                )

                setOnMapTouchListener {
                    repair_scroll.requestDisallowInterceptTouchEvent(it.action != MotionEvent.ACTION_UP)
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().request(
            requestUrl = BaseUrl.repairDetail,
            params = *arrayOf("id" to intent.getExtra("id")),
            onResult = {
                val obj = JSONObject(it)

                mTel = obj.optNotNull("phone")
                repair_name.text = obj.optNotNull("name")
                repair_tel.text = "维修电话：$mTel"
                repair_work.text =
                    "工作时间：${obj.optNotNull("begindate")} - ${obj.optNotNull("enddate")}"
                repair_adress.text = obj.optNotNull("address")

                val img = obj.optNotNull("img")
                if (img.isNotEmpty()) {
                    mViewPager.refreshData(img.split(","))
                }

                mLat = obj.optNotNull("lat")
                mLng = obj.optNotNull("lon")
                setLocation(mLat, mLng)
            }
        )
    }

    private fun setLocation(lat: String, lng: String) {
        val mLatLng = LatLng(
            lat.toNotDouble(),
            lng.toNotDouble()
        ).convertGpsToBaidu()

        repair_map.map.apply {
            isMyLocationEnabled = true
            setMyLocationData(
                MyLocationData.Builder()
                    .accuracy(0f)                 //精度圈半径
                    .latitude(mLatLng.latitude)   //纬度
                    .longitude(mLatLng.longitude) //经度
                    .build()
            )

            animateMapStatus(
                MapStatusUpdateFactory.newMapStatus(
                    MapStatus.Builder()
                        .target(mLatLng)
                        .zoom(18f)
                        .build()
                )
            )
        }
    }

    override fun onPause() {
        super.onPause()
        mViewPager.stopLoop()
        repair_map.onPause()
    }

    override fun onResume() {
        super.onResume()
        mViewPager.startLoop()
        repair_map.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        repair_map.map.isMyLocationEnabled = false
        repair_map.onDestroy()
    }

}